package sfeir.ergosum.service;

import sfeir.ergosum.HiveActivity;
import sfeir.ergosum.R;
import sfeir.ergosum.dao.DatabaseConnection;
import sfeir.ergosum.dao.DatabaseProvider;
import sfeir.ergosum.model.Address;
import sfeir.ergosum.model.Email;
import sfeir.ergosum.model.Person;
import sfeir.ergosum.model.Tel;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.Contacts;
import android.provider.Contacts.ContactMethods;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.widget.RemoteViews;
import android.widget.Toast;

public class ImportService extends Service {

    public static final String CONTACT_ADDED = "Contact_Added";
    public static final String CONTACT_IMPORT_FINISHED = "Contact_Import_Finished";
    public static final int NOTIFICATION_CONTACT_ADDED = 1;
    public static final int NOTIFICATION_IMPORT_FINISHED = 2;
    private Thread mThread;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if (null != mThread) {
            Toast.makeText(this, "Import already running", 2000).show();
            return;
        }
        System.out.println("Import" + startId);
        mThread = new Thread(new ImportContacts());
        mThread.start();
        // mProgressDialog.dismiss();
    }

    private class ImportContacts implements Runnable {

        @Override
        public void run() {
            // Debug.startMethodTracing("import");
            final ContentResolver resolver = getContentResolver();
            final Uri uri = Contacts.People.CONTENT_URI;
            String[] projection = new String[] { People._ID, People.NAME, People.NOTES, People.NUMBER };
            Cursor cur = resolver.query(uri, projection, null, null, null);

            final NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            final PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(
                    ImportService.this, HiveActivity.class), 0);
            final Notification notif = new Notification(R.drawable.icon, "Importing contacts", System
                    .currentTimeMillis());
            notif.contentView = new RemoteViews(getPackageName(), R.layout.notification_progress_view);
            notif.contentIntent = launchIntent;

            // startManagingCursor(cur); Only useful for activities
            // final ProgressDialog mProgressDialog = new
            // ProgressDialog(activity);

            DatabaseProvider dp = null;
            try {
                dp = new DatabaseProvider(new DatabaseConnection(getApplicationContext()));
                dp.open();
                Person p = null;

                int i = 0;
                if (cur.moveToFirst()) {
                    do {
                        p = addContact(cur, resolver);
                        if (p != null) {
                            dp.addContact(p, p.getUrl());
                            // sendBroadcast(new
                            // Intent(CONTACT_ADDED).putExtra("url",
                            // p.getFullName()));
                            if (0 == i % 5) {
                                notif.contentView.setProgressBar(R.id.NotifProgressBar, cur.getCount(), cur
                                        .getPosition(), false);
                                notif.contentView.setTextViewText(R.id.textImportNotification, "Import : "
                                        + cur.getPosition() + "/" + cur.getCount());
                                mNM.notify(NOTIFICATION_CONTACT_ADDED, notif);
                            }
                        }
                        // if (cur != null && mProgressDialog != null)
                        // mProgressDialog.setProgress(cur.getPosition());
                        ++i;
                    } while (cur.moveToNext()/* && ++i < 50 */);

                    mNM.cancel(NOTIFICATION_CONTACT_ADDED);
                    notif.tickerText = "Import finished";
                    notif.setLatestEventInfo(getApplicationContext(), "Import finished", "Contacts import is finished",
                            launchIntent);
                    mNM.notify(NOTIFICATION_IMPORT_FINISHED, notif);
                    sendBroadcast(new Intent(CONTACT_IMPORT_FINISHED));
                }
            } finally {
                dp.close();
                cur.close();
                cur = null;
                // Debug.stopMethodTracing();
                stopSelf();
            }
        }

    }

    protected Person addContact(Cursor cur, ContentResolver resolver) {
        String name = cur.getString(cur.getColumnIndex(People.NAME));
        String id = cur.getString(cur.getColumnIndex(Contacts.People._ID));
        String notes = cur.getString(cur.getColumnIndex(People.NOTES));
        // System.out.println(name);
        Person p = null;
        if (name != null && !name.equalsIgnoreCase("")) {
            p = new Person();

            // firstname name
            int n = name.indexOf(" ");
            if (n != (-1)) {
                String first = name.substring(0, n);
                String last = name.substring(n);

                p.setName(last);
                p.setFirstname(first);
            } else {
                p.setName(name);
                p.setFirstname("");
            }

            if (notes != null)
                p.setAboutMe(notes);
        }

        p = addContactMethodsToPerson(resolver, id, p);
        if (p != null) {
            addPhonesToContact(resolver, id, p);

            String url = "content://contacts/people/" + id;
            p.setPhoto(url);

            p.setUrl(url);
        }
        return p;
    }

    private Person addContactMethodsToPerson(ContentResolver resolver, String id, Person p) {

        Uri mailsUri = Contacts.ContactMethods.CONTENT_URI;
        Cursor curCM = resolver.query(mailsUri, null, "person=" + id, null, null);
        // activity.startManagingCursor(curCM);

        try {
            if (curCM.moveToFirst()) {
                int cmType;
                String cmContent;
                int kind;
                do {
                    kind = curCM.getInt(curCM.getColumnIndex(ContactMethods.KIND));
                    cmType = curCM.getInt(curCM.getColumnIndex(ContactMethods.TYPE));
                    cmContent = curCM.getString(curCM.getColumnIndex(ContactMethods.DATA));

                    /*
                     * EMAILS informations
                     */
                    if (kind == Contacts.KIND_EMAIL) {
                        Email e = new Email(cmContent);
                        if (cmType != 0) {
                            switch (cmType) {
                            case Contacts.ContactMethods.TYPE_HOME:
                                e.setTypeEmail(Email.PERSONAL_EMAIL);
                                break;
                            case Contacts.ContactMethods.TYPE_WORK:
                                e.setTypeEmail(Email.PROFESSIONNAL_EMAIL);
                                break;
                            default:
                                e.setTypeEmail(Email.UNKNOWN);
                            }
                        }
                        if (p == null || p.getName() == null || p.getName().equalsIgnoreCase("")) {
                            p = new Person();
                            p.setFirstname("");
                            String name = e.getEmail();
                            // firstname name
                            int n = name.indexOf("@");
                            if (n != (-1)) {
                                String firstname = name.substring(0, n);
                                p.setName(firstname);
                            } else {
                                p.setName(name);
                            }

                        }
                        if (p != null)
                            p.getEmails().add(e);
                    }
                    /*
                     * POSTAL ADDRESSES
                     */
                    if (kind == Contacts.KIND_POSTAL) {
                        Address a = new Address(cmContent);
                        if (cmType != 0) {
                            switch (cmType) {
                            case Contacts.ContactMethods.TYPE_HOME:
                                a.setType(Address.PERSONAL_ADDRESS);
                                break;
                            case Contacts.ContactMethods.TYPE_WORK:
                                a.setType(Address.PROFESSIONNAL_ADDRESS);
                                break;
                            default:
                                a.setType(Address.DEFAULT_ADDRESS);
                            }
                        }
                        if (p != null)
                            p.getAddresses().add(a);
                    }
                } while (curCM.moveToNext());
            }
        } finally {
            curCM.close();
            curCM = null;
        }
        return p;
    }

    private void addPhonesToContact(ContentResolver resolver, String id, Person p) {
        /*
         * PHONES informations
         */
        Uri phonesUri = Contacts.Phones.CONTENT_URI;
        String[] projection = new String[] { Phones.TYPE, Phones.NUMBER };
        Cursor curPhone = resolver.query(phonesUri, projection, "person=" + id, null, null);
        // activity.startManagingCursor(curPhone);
        Tel t = null;
        if (curPhone.moveToFirst()) {
            int type;
            String number;
            do {
                type = curPhone.getInt(curPhone.getColumnIndex(Contacts.Phones.TYPE));
                number = curPhone.getString(curPhone.getColumnIndex(Contacts.Phones.NUMBER));

                if (number != null && !number.equalsIgnoreCase("")) {
                    t = new Tel();
                    t.setPhoneNumber(number);
                }
                if (type != 0) {
                    switch (type) {
                    case Contacts.Phones.TYPE_MOBILE:
                        t.setType(Tel.MOBILE_LINE);
                        break;
                    case Contacts.Phones.TYPE_HOME:
                        t.setType(Tel.HOME_LANDLINE);
                        break;
                    case Contacts.Phones.TYPE_WORK:
                        t.setType(Tel.PROFESSIONNAL_LINE);
                    default:
                        t.setType(Tel.UNKNOWN_LINE);
                    }
                }
                p.getTels().add(t);
            } while (curPhone.moveToNext());
        }

        curPhone.close();
    }
}
